package util;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.lychie.jexcel.WritableExcel;
import org.lychie.jexcel.demo.model.Employee;
import org.lychie.jexcel.model.Body;
import org.lychie.jexcel.model.ValueFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *  向文件中写入内容 
 * @author Administrator
 *
 */
public class WriteContentUtil {
	
	 public static  Logger LOGGER = LoggerFactory.getLogger(WriteContentUtil.class);
	 
	 public static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	/**
	 * @param PropertyHead  头部属性
	 * 
	 * @param initData     初始化数据
	 * 
	 * @param writePath    写入文件路径        
	 */
	public static void writeToFile(List<Map<String,Object>> PropertyHead,List<?> initData,String writePath){
		// 创建一个可写的EXCEL对象
		WritableExcel excel = new WritableExcel(initData);
		// 设置POJO属性与EXCEL单元格的映射关系
		if(null!=PropertyHead&&PropertyHead.size()>0){
			for(Map<String,Object> entry:PropertyHead){
				Iterator<Entry<String, Object>> it = entry.entrySet().iterator();
				  while (it.hasNext()) {
					   Map.Entry<String, Object> map = it.next();
					   String key=map.getKey()==null?"":map.getKey().toString();
					   String value=map.getValue()==null?"":map.getValue().toString();
					   LOGGER.info("key===>"+key+",====value>>"+value);
					   excel.setMapper(key,value);
				  }
			}
		}
		// 单元格值格式对象
		ValueFormat format = excel.getValueFormat();
		// 设置薪资显示格式为货币格式
		format.set("salary", ValueFormat.CURRENCY_FORMAT);
		// 主体对象
		Body body = excel.getBody();
		// 设置单元格内容水平方向居中
		body.setHorizontalAlignment(Body.HORIZONTAL_CENTER);
		
		
		// 将对象内容写出到EXCEL文档
		
		excel.write(new File(writePath));
		
	}
	
	private static List<Employee> getData() {
		List<Employee> list = new ArrayList<Employee>();
		list.add(new Employee("杨忠杰"));
		list.add(new Employee("叶水燕"));
		list.add(new Employee("杨晓婷"));
		list.add(new Employee("叶国珠"));
		list.add(new Employee("何国群"));
		return list;
	}
	
	//测试
	public static void main(String[] args) {
		List<Map<String,Object>>  ProHeadList=new ArrayList<Map<String,Object>>();
		Map<String,Object> headmap=new HashMap<String, Object>();
		headmap.put("id", "编号");
		headmap.put("name", "姓名");
		headmap.put("hiredate", "入职日期");
		headmap.put("salary", "薪资");
		ProHeadList.add(headmap);
		
		LOGGER.info("=======start writing ================="+sdf.format(new Date()));
		
		writeToFile(ProHeadList,getData(),"src/main/resources/employee.xlsx");
		
		LOGGER.info("=======End writing ==================="+sdf.format(new Date()));
	}
}
